package com.bw.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.domain.SysUser;
import com.bw.service.SysUserService;
import com.bw.utils.common.JWTUtils;
import com.bw.utils.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RequestMapping("auth")
@RestController
public class AuthController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("login")
    public Result login(@RequestBody SysUser sysUser) {
        String dbCode = (String) redisTemplate.opsForValue().get(sysUser.getUuid());
        if (!dbCode.equals(sysUser.getCode())) {
            return Result.fail("验证码不正确");
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getName, sysUser.getName());
        SysUser dbUser = sysUserService.getOne(wrapper);
        if (null == dbUser) {
            return Result.fail("用户名不存在");
        }
        String s = DigestUtil.md5Hex(sysUser.getPassword() + salt);
        if (!dbUser.getPassword().equals(s)){
            return Result.fail("密码不对");
        }
        String token = JWTUtils.createToken(dbUser.getId(), 1 * 60);
        return Result.success(token);
    }

    @RequestMapping("getCode")
    public void getCode(String uuid, HttpServletResponse response) throws IOException {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        captcha.write(response.getOutputStream());
        redisTemplate.opsForValue().set(uuid,captcha.getCode(),5, TimeUnit.MINUTES);
    }

    public static final String salt="2111";
    @PostConstruct
    public void initPWD(){
        String pwd="123";
        String md5Hex = DigestUtil.md5Hex(pwd + salt);
        System.out.println("我的密码是123456，md5加密后是"+md5Hex);
    }
}